/*
 * hx711.c
 *
 *  Created on: Feb 27, 2025
 *      Author: zhang
 */

#include "main.h"
#include "gpio.h"
#include "hx711.h"

#define GapValue 202 //传感器系数

uint32_t weight_first = 0;//首次质量
uint32_t weight_real = 0;//每次读取的实际值


float P=1;
float P_;  //对应公式中的p'
float X=0;
float X_;  //X'
float K=0;
float Q=0.01;//噪声
//float R=0.2;  //R如果很大，更相信预测值，那么传感器反应就会迟钝，反之相反
float R=0.5;
float distance=0;
float distance1=0;
float KLM(float Z)
{
  X_=X+0;
  P_=P+Q;
  K=P_/(P_+R);
  X=X_+K*(Z-X_);
  P=P_-K*P_;
  return X;
}

int32_t HX711_Read_Data(){
	uint32_t Count=0;
	uint8_t i;
	HAL_GPIO_WritePin(HX711_SCL_GPIO_Port, HX711_SCL_Pin, GPIO_PIN_RESET);
	while(HAL_GPIO_ReadPin(HX711_SDA_GPIO_Port, HX711_SDA_Pin));
	for(i=0;i<24;i++){
		HAL_GPIO_WritePin(HX711_SCL_GPIO_Port, HX711_SCL_Pin, GPIO_PIN_SET);
		Count=Count<<1;
		if(HAL_GPIO_ReadPin(HX711_SDA_GPIO_Port, HX711_SDA_Pin)){
			Count++;
		}
		HAL_GPIO_WritePin(HX711_SCL_GPIO_Port, HX711_SCL_Pin, GPIO_PIN_RESET);

	}
	HAL_GPIO_WritePin(HX711_SCL_GPIO_Port, HX711_SCL_Pin, GPIO_PIN_SET);
	Count = Count ^ 0x800000;
	HAL_GPIO_WritePin(HX711_SCL_GPIO_Port, HX711_SCL_Pin, GPIO_PIN_RESET);
	return Count;
}


uint32_t WeightReal(void)
{
    weight_real = HX711_Read_Data();//实际质量计算
	weight_real = (int32_t)(weight_real-weight_first);
	weight_real = (int32_t)((float)weight_real/GapValue);
		//printf("重量为：%dg\n",weight_real);
	if(weight_real>5000){weight_real=0;};
	weight_real = (uint32_t)KLM(weight_real);
		return weight_real;
}
